package com.aken.imdemo.net

import android.content.Context
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import com.aken.imdemo.R
import com.aken.imdemo.model.LoginData
import com.aken.imdemo.model.ReceivedLiveHistory
import com.aken.imdemo.model.SendMessageCallbackData
import com.aken.imdemo.util.DisplayUtil.sp2dip
import com.aken.imdemo.util.SpannableMaker
import com.orhanobut.logger.Logger
import com.tencent.imsdk.TIMCallBack
import com.tencent.imsdk.TIMGroupManager
import com.tencent.imsdk.v2.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

object TIMConversationManager {
    fun connectTIMService(context: Context) {
        val v2TIMSDKConfig = V2TIMSDKConfig()
        v2TIMSDKConfig.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_WARN)
        V2TIMManager.getInstance()
            .initSDK(context, NetWorkManager.TESTAPPID, v2TIMSDKConfig, object :
                V2TIMSDKListener() {
                override fun onConnecting() {
                    Logger.d("正在连接到腾讯云服务器")
                }

                override fun onConnectSuccess() {
                    Logger.d("已经成功连接到腾讯云服务器")
                }

                override fun onConnectFailed(code: Int, error: String?) {
                    Logger.d("连接腾讯云服务器失败")
                }

            })
    }

    fun connectLive(userName: String, password: String, callback: CommonRequestCallbackImp) {
        NetWorkManager.apiService?.login(userName, password)
            ?.enqueue(object : Callback<LoginData> {
                override fun onFailure(call: Call<LoginData>, t: Throwable) {
                    callback.onError("登录服务器失败")
                }

                override fun onResponse(call: Call<LoginData>, response: Response<LoginData>) {
                    val loginData = response.body()
                    loginData?.let {
                        if (it.error == 2000000) {

                            Logger.d("登录服务器成功--> $it")

                            NetWorkManager.SDKAPPID = it.data.user_id
                            NetWorkManager.USERSIG = it.data.user_sig
                            NetWorkManager.TOKEN = it.data.token

                            //直播间ID
                            V2TIMManager.getInstance()
                                .login(it.data.user_id.toString(), it.data.user_sig, object :
                                    V2TIMCallback {
                                    override fun onError(code: Int, desc: String) {
                                        callback.onError("登录腾讯IM失败：$desc")
                                    }

                                    override fun onSuccess() {
                                        Logger.d("登录腾讯IM成功")

                                        TIMGroupManager.getInstance().applyJoinGroup(
                                            NetWorkManager.TESTLIVEID,
                                            "进入直播群",
                                            object :
                                                TIMCallBack {
                                                override fun onSuccess() {
                                                    callback.onSuccess()
                                                }

                                                override fun onError(p0: Int, p1: String?) {
                                                    callback.onError(p1)
                                                }
                                            })
                                    }
                                })
                        }
                    }
                }


            })
    }

    fun addMessageListener(handler: MessageHandleSucImp) {
        V2TIMManager.getInstance().addSimpleMsgListener(object : V2TIMSimpleMsgListener() {
            override fun onRecvGroupTextMessage(
                msgID: String,
                groupID: String,
                sender: V2TIMGroupMemberInfo,
                text: String
            ) {
                Logger.d("收到信息$text")
                val builder = SpannableStringBuilder()
                val colorSpan =
                    ForegroundColorSpan(Color.parseColor("#FC8952"))

                builder.append(
                    sender.nickName + "：",
                    colorSpan,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                )

                handler.handelMessage(builder, text)
            }
        })
    }

    fun sendMessage(msgText: String, context: Context, handler: MessageHandleSucImp) {
        Logger.d("发送的内容是：$msgText")
        NetWorkManager.apiService?.sendMessage(1, msgText, NetWorkManager.TOKEN)
            ?.enqueue(object : Callback<SendMessageCallbackData?> {
                override fun onResponse(
                    call: Call<SendMessageCallbackData?>,
                    response: Response<SendMessageCallbackData?>
                ) {
                    Logger.d("发到服务器了，回传成功")
                    if (response.body()?.error == 2000000) {
                        val callbackData = response.body()?.data
                        callbackData?.let {
                            Logger.d("回传的内容有效")

                            //转发content到TIM服务器
                            V2TIMManager.getInstance().sendGroupTextMessage(
                                callbackData.content,
                                NetWorkManager.TESTLIVEID,
                                V2TIMMessage.V2TIM_PRIORITY_NORMAL,
                                object : V2TIMValueCallback<V2TIMMessage?> {
                                    override fun onError(i: Int, s: String) {
                                        Logger.d("发送回传信息到TIM服务器失败：$s")
                                    }

                                    override fun onSuccess(v2TIMMessage: V2TIMMessage?) {
                                        Logger.d("发送回传信息到TIM服务器成功： " + callbackData.content)
                                        val builder = SpannableStringBuilder()
                                        if (callbackData.isVip == 1) {
                                            val imageSpan =
                                                ImageSpan(context, R.drawable.ic_vip)
                                            builder.append(
                                                "VIP",
                                                imageSpan,
                                                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                                            )
                                            builder.append(" ")
                                        }
                                        if (callbackData.isSupreme == 1) {
                                            val imageSpan =
                                                ImageSpan(context, R.drawable.ic_plus)
                                            builder.append(
                                                "PLUS",
                                                imageSpan,
                                                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                                            )
                                            builder.append(" ")
                                        }
                                        /*
                            if (user.isJoinClub()) {
                                ImageSpan imageSpan = new ImageSpan(MainActivity.this, R.drawable.ic_club);
                                builder.append("CLUB", imageSpan, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                builder.append(" ");
                            }*/
                                        val colorSpan =
                                            ForegroundColorSpan(Color.parseColor("#FC8952"))
                                        val absoluteSizeSpan = AbsoluteSizeSpan(
                                            sp2dip(context, 18f),
                                            true
                                        )
                                        val start = builder.length
                                        builder.append(
                                            callbackData.u_name + "：",
                                            colorSpan,
                                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                                        )

                                        handler.handelMessage(builder, callbackData.content)
                                    }
                                })
                        }
                    }
                    else {
                        handler.error("回传的信息有问题：${response.body()}")
                    }
                }

                override fun onFailure(
                    call: Call<SendMessageCallbackData?>,
                    t: Throwable
                ) {
                    Logger.d("发送消息失败")
                }
            })
    }

    fun getLiveMessageList(context: Context, handler: MessageHandleSucImp) {
        NetWorkManager.apiService?.getLiveMessageList(1)
            ?.enqueue(object : Callback<ReceivedLiveHistory?> {
                override fun onResponse(
                    call: Call<ReceivedLiveHistory?>,
                    response: Response<ReceivedLiveHistory?>
                ) {
                    val receivedLiveHistory = response.body()
                    if (receivedLiveHistory != null && receivedLiveHistory.error == 2000000) {
                        Logger.d("拉取直播历史消息成功")
                        val historyList =
                            receivedLiveHistory.data.list
                        for ((_, _, _, content, _, _, _, _, _, _, _, _, _, _, _, issupreme, _, isvip, _, _, _, username) in historyList) {
                            val builder = SpannableStringBuilder()
                            if (isvip == 1) {
                                val imageSpan =
                                    ImageSpan(context, R.drawable.ic_vip)
                                builder.append("VIP", imageSpan, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
                                builder.append(" ")
                            }
                            if (issupreme == 1) {
                                val imageSpan =
                                    ImageSpan(context, R.drawable.ic_plus)
                                builder.append("PLUS", imageSpan, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
                                builder.append(" ")
                            }
                            /*
                        if (user.isJoinClub()) {
                            ImageSpan imageSpan = new ImageSpan(MainActivity.this, R.drawable.ic_club);
                            builder.append("CLUB", imageSpan, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                            builder.append(" ");
                        }*/
                            val colorSpan =
                                ForegroundColorSpan(Color.parseColor("#FC8952"))
                            val absoluteSizeSpan =
                                AbsoluteSizeSpan(sp2dip(context, 18f), true)
                            val start = builder.length
                            builder.append(
                                "$username：",
                                colorSpan,
                                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                            )
                            val end = builder.length
                            // builder.setSpan(absoluteSizeSpan, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            val spannable = SpannableMaker.buildEmotionSpannable(
                                context,
                                content,
                                40
                            )
                            builder.append(spannable)
                            handler.handelMessage(builder, content)
                        }
                    } else {
                        handler.error("拉取直播历史消息失败")
                    }
                }

                override fun onFailure(
                    call: Call<ReceivedLiveHistory?>,
                    t: Throwable
                ) {
                    handler.error("连接失败---直播历史消息")
                }
            })

    }
}